package com.wtzz.police.base.config;

import com.wtzz.police.base.entity.Department;
import com.wtzz.police.base.entity.User;
import com.wtzz.police.base.model.enums.Role;
import com.wtzz.police.base.repository.DepartmentRepository;
import com.wtzz.police.base.repository.UserRepository;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;

/**
 * 服务初始化
 *
 * @author zxh
 * @date 2019-04-01
 */
@Component
@Transactional
@Slf4j
public class SystemInitialize implements InitializingBean {
    @Autowired
    DepartmentRepository deptRepo;
    @Autowired
    UserRepository userRepository;

    @Override
    @Transactional
    public void afterPropertiesSet() throws Exception {
        initializeDepartment();
    }

    private void initializeDepartment() {
        if (deptRepo.count() == 0) {
            Department department = new Department();
            department.setCode("0");
            department.setName("系统管理");
            department.setFullname("系统管理");
            deptRepo.save(department);
            log.info("插入初始部门{},id为{}", department.getName(), department.getId());
        }
        if (userRepository.count() == 0) {
            User user = new User();
            user.setUsername("admin");
            user.setPassword(DigestUtils.md5DigestAsHex("admin".getBytes()));
            user.setFullname("管理员");
            user.setDepartment(null);
            user.setRole(Role.ADMIN);
            user.setDepartment(deptRepo.findByCode("0").orElse(null));
            userRepository.save(user);
            log.info("插入初始管理员{},id为{}", user.getFullname(), user.getId());
        }
    }
}
